package com.shop.service.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.service.module.entity.DeptEntity;
import com.shop.service.module.entity.Result;
import com.shop.service.module.entity.UserEntity;
import com.shop.service.module.mapper.DeptMapper;
import com.shop.service.module.mapper.UserMapper;
import com.shop.service.module.service.DeptService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptEntity> implements DeptService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result getListUser() {
        //查询出所有部门信息
        List<DeptEntity> deptEntities = baseMapper.selectList(null);
        //查询出所有员工信息
        QueryWrapper queryWrapper = new QueryWrapper();
        //0代表是员工
        queryWrapper.eq("type", 0);
        List<UserEntity> userEntities = userMapper.selectList(queryWrapper);
        deptEntities.forEach(deptEntity -> packChildren(deptEntity, userEntities));

        return Result.end(200, deptEntities, "查询成功");
    }

    @Override
    public Result addUser(Long[] ids, Long id) {

        List<UserEntity> userEntities = userMapper.selectBatchIds(Arrays.asList(ids));
        userEntities.forEach(user -> {
            user.setDeptId(Integer.valueOf(Math.toIntExact(id)));
            userMapper.updateById(user);
        });

        return Result.end(200,"", "添加成功");
    }

    @Override
    public Result deleteUser(Long id) {
        UserEntity userEntity = userMapper.selectById(id);
        userEntity.setDeptId(-1);
        userMapper.updateById(userEntity);

        return Result.end(200,"", "删除成功");
    }

    private void packChildren(DeptEntity deptEntity, List<UserEntity> userEntities) {
        List<UserEntity> collect = userEntities.stream().filter(userEntity ->
                Long.valueOf(userEntity.getDeptId()) == deptEntity.getId()).collect(Collectors.toList());
        deptEntity.setChildren(collect);

    }
}
